﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using WebCoreAPI.Identity;

namespace WebCoreAPI.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class IdentityController : ControllerBase
    {
        private readonly UserManager<MyUser> userManager;
        private readonly RoleManager<MyRole> roleManager;

        public IdentityController(UserManager<MyUser> userManager, RoleManager<MyRole> roleManager)
        {
            this.userManager = userManager;
            this.roleManager = roleManager;
        }

        /// <summary>
        /// 创建角色，用户
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult<string>> CreateInfo()
        {
            //添加角色
            if (!await roleManager.RoleExistsAsync("admin"))
            {
                MyRole role = new MyRole { Name = "admin" };
                IdentityResult result = await roleManager.CreateAsync(role);
                if (!result.Succeeded) return BadRequest("创建角色 失败");
            }
            //添加用户
            MyUser user = await userManager.FindByNameAsync("Feng");
            if (null == user)
            {
                user = new MyUser { UserName = "Feng" };
                IdentityResult result = await userManager.CreateAsync(user, "123456");
                if (result.Succeeded) return BadRequest("创建用户 失败");
            }
            //为用户添加角色
            if (!await userManager.IsInRoleAsync(user, "admin"))
            {
                var result = await userManager.AddToRoleAsync(user, "admin");
                if (!result.Succeeded) return BadRequest("为用户添加角色失败");
            }
            return "OK";
        }

        /// <summary>
        /// 登录处理
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="pwd">密码</param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult<string>> LoginIndentity(string userName, string pwd)
        {
            var user = await userManager.FindByNameAsync(userName);
            if (null == user) return NotFound($"用户名不存在{userName}");
            if (await userManager.IsLockedOutAsync(user)) return BadRequest("用户被锁定，锁定时间：" + user.LockoutEnd);
            if (await userManager.CheckPasswordAsync(user, pwd))
            {
                await userManager.ResetAccessFailedCountAsync(user); //重置登录失败
                return Ok("成功");
            }
            else await userManager.AccessFailedAsync(user); //记录登录失败
            return BadRequest("登录失败");
        }

        /// <summary>
        /// 重置密码，发送Token
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult<string>> SendToken(string userName)
        {
            var user = await userManager.FindByNameAsync(userName);
            if (null == user) return BadRequest("用户名不存在");
            string token = await userManager.GeneratePasswordResetTokenAsync(user);
            return Ok("Token:" + token);
        }
        /// <summary>
        /// 重置密码
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="token"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult<string>> ResetPassword(string userName,string token,string pwd)
        {
            var user = await userManager.FindByNameAsync(userName);
            if (null == user) return BadRequest("用户名不存在");
           var result= await userManager.ResetPasswordAsync(user, token, pwd);
            if (result.Succeeded) return Ok("更新密码成功");
            return BadRequest("更新密码失败");
        }
    }
}
